package com.qdu.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.qdu.commons.RedisKey;
import com.qdu.commons.Result;
import com.qdu.entity.Mytrace;
import com.qdu.entity.Route;
import com.qdu.entity.RouteTrace;
import com.qdu.entity.User;
import com.qdu.mq.RabbitProducer;
import com.qdu.service.impl.CompleteServiceImpl;
import com.qdu.service.impl.MytraceServiceImpl;
import com.qdu.service.impl.RouteServiceImpl;
import com.qdu.service.impl.UserServiceImpl;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ellery2018
 * @since 2022-03-09
 */
@Slf4j
@RestController
@RequestMapping("/mytrace")
public class MytraceController {

    @Autowired
    MytraceServiceImpl mytraceService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private RabbitProducer rabbitProducer;

    @Autowired
    RouteTraceController routeTraceController;

    @PostMapping("/addTrace")
    @ApiOperation(value = "将个人轨迹信息添加到数据库中")
    public Result addTrace(@RequestBody List<Mytrace> mytraces){
        // 使用消息队列进行入库操作，防止大量瞬时插入操作
        log.info("运动轨迹发送给mq等待消费");
        if (mytraces == null || mytraces.size() == 0) {
            return Result.FAIL("轨迹为空");
        }
        rabbitProducer.addMytraceQueue(mytraces);
        return Result.SUCCESS("轨迹已记录");
    }

    @GetMapping("/getMytrace")
    @ApiOperation(value = "获取用户在当前景点的运动轨迹")
    public Result getMytrace(int routeId ,int userId) {
//        先从redis获取
        if (redisTemplate.hasKey(RedisKey.MYROUTE_TRACE+routeId+"&"+userId)){
            log.info("从redis获取自己的运动轨迹");
            List<Mytrace> mytraces = redisTemplate.opsForList().range(RedisKey.MYROUTE_TRACE+routeId+"&"+userId, 0, -1);
            return Result.SUCCESS(mytraces);
        }

        List<Mytrace> mytrace  = mytraceService.list(new QueryWrapper<Mytrace>().eq("routeId",routeId).eq("userId", userId));
        if (mytrace.size()==0){
            return Result.FAIL("无路线运动轨迹轨迹");
        }
        if (Objects.nonNull(mytrace.get(0).getTheFirstDate())) {
            Collections.sort(mytrace, Comparator.comparing(Mytrace::getTheFirstDate));
        }
        if (redisTemplate.hasKey(RedisKey.MYROUTE_TRACE+routeId+"&"+userId)) redisTemplate.delete(RedisKey.MYROUTE_TRACE+routeId+"&"+userId);
        redisTemplate.opsForList().rightPushAll(RedisKey.MYROUTE_TRACE+routeId+"&"+userId, mytrace);
        return Result.SUCCESS(mytrace);
    }

}
